<template>
    <div class="add-shijuan-container">
      <el-form 
        ref="ruleFormRef" 
        :model="ruleForm" 
        :rules="rules" 
        label-width="100px"
        class="compact-form"
      >
        <!-- 基本信息 -->
        <el-form-item label="年级" prop="level">
          <el-select 
            v-model="ruleForm.level" 
            placeholder="请选择年级" 
            @change="handleGradeChange"
            :loading="loading"
            style="width: 300px"
          >
            <el-option 
              :label="item.name" 
              :value="item.value" 
              v-for="item in levelStore.list" 
              :key="item.value" 
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="学科" prop="subject">
          <el-select 
            v-model="ruleForm.subject" 
            placeholder="请先选择年级"
            :disabled="!ruleForm.level"
            :loading="loading"
            style="width: 300px"
          >
            <el-option 
              :label="subject.name" 
              :value="subject.id" 
              v-for="subject in filteredSubjects" 
              :key="subject.id" 
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="试卷类型" prop="paperType">
          <el-select 
            v-model="ruleForm.paperType" 
            @change="handlePaperTypeChange"
            style="width: 300px"
          >
            <el-option 
              :label="item.name" 
              :value="item.value" 
              v-for="item in shijuanStore.shijuanclass" 
              :key="item.value" 
            />
          </el-select>
        </el-form-item>
        
        <!-- 日期范围选择器 -->
        <el-form-item 
          v-if="showDatePicker"
          label="日期范围" 
          prop="dateRange"
        >
          <el-date-picker
            v-model="ruleForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            style="width: 400px"
          />
        </el-form-item>
        
        <el-form-item label="试卷名称" prop="name">
          <el-input 
            v-model="ruleForm.name" 
            placeholder="请输入试卷名称"
            style="width: 400px"
          />
        </el-form-item>
        
        <!-- 动态标题区域 - 紧凑布局 -->
        <div v-for="(title, index) in ruleForm.titles" :key="index" class="dynamic-title-item compact">
          <el-form-item 
            :label="`标题 ${index + 1}`" 
            class="title-item"
          >
            <div class="title-content">
              <el-input 
                v-model="title.value" 
                placeholder="请输入标题内容"
                style="width: 300px;"
                size="small"
              />
              <div class="title-actions">
                <el-button type="danger" size="small" @click="removeTitle(index)" plain>
                  删除
                </el-button>
                <el-button type="primary" size="small" @click="addQuestions(index)" plain>
                  添加题目
                </el-button>
              </div>
            </div>
            
            <!-- 题目列表 - 紧凑布局 -->
            <div class="questions-list compact" v-if="title.questions && title.questions.length > 0">
              <div 
                v-for="(q, qIndex) in title.questions" 
                :key="qIndex" 
                class="question-item compact"
              >
                <div class="question-content-wrapper">
                  <span class="question-index">{{ qIndex + 1 }}.</span>
                  <span class="question-text">{{ q.content }}</span>
                  <div class="question-actions">
                    <el-button 
                      type="danger" 
                      size="small" 
                      @click="removeQuestion(index, qIndex)"
                      plain
                    >删除</el-button>
                  </div>
                </div>
              </div>
            </div>
          </el-form-item>
        </div>
        
        <el-form-item label="建议时长" prop="duration">
          <el-input 
            v-model="ruleForm.duration" 
            placeholder="请输入建议时长（分钟）" 
            type="number" 
            min="0" 
            style="width: 200px"
          >
            <template #append>分钟</template>
          </el-input>
        </el-form-item>
        
        <el-form-item class="form-actions">
          <el-button type="primary" @click="submitForm(ruleFormRef)">
            提交
          </el-button>
          <el-button @click="resetForm(ruleFormRef)">重置</el-button>
          <el-button type="success" @click="addTitle">
            添加标题
          </el-button>
        </el-form-item>
      </el-form>
      
      <!-- 添加题目对话框 -->
      <Addzujiantimu ref="addQuestionDialogRef" @addQuestions="handleAddQuestions" />
    </div>
  </template>
  
  <script lang="ts" setup>
  import { ref, computed, onMounted, reactive, watch } from 'vue'
  import { type FormInstance, type FormRules, ElMessage } from 'element-plus'
  import { useLevelStore } from '@/stores/level'
  import { useRouter } from 'vue-router'
  import { getSubjectList, type Subject } from '@/api/juanti'
  import { useshijuanStore } from '@/stores/juanti'
  import Addzujiantimu from './Addzujiantimu.vue'
  import type { QuestionItem } from '@/api/juanti' // 导入题目类型
  
  // 创建路由实例
  const router = useRouter()
  const levelStore = useLevelStore()
  const shijuanStore = useshijuanStore()
  const addQuestionDialogRef = ref<InstanceType<typeof Addzujiantimu>>()
  
  // 首先声明和初始化所有变量
  const loading = ref(false)
  const subjectList = ref<Subject[]>([])
  const filteredSubjects = ref<Subject[]>([])
  const ruleFormRef = ref<FormInstance>()
  
  // 存储当前操作的标题索引
  const currentTitleIndex = ref(-1)
  
  // 正确初始化 ruleForm
  const ruleForm = reactive({
    name: '',
    level: null as number | null,
    subject: '',
    paperType: 1,
    duration: '',
    dateRange: null as [string, string] | null,
    id: null,
    levelName: "",
    // 标题数组
    titles: [] as Array<{
      value: string
      questions: Array<{
        id: number
        questionType: number
        content: string
        difficulty: number
      }>
    }>
  })
  
  // 计算属性，控制日期选择器是否显示
  const showDatePicker = computed(() => {
    return ruleForm.paperType === 2
  })
  
  // 年级变化处理
  const handleGradeChange = (val: number) => {
    const level = levelStore.list.find(item => item.value == val)
    ruleForm.levelName = level?.name || ""
  }
  
  // 试卷类型变化处理
  const handlePaperTypeChange = (value: number) => {
    if (value !== 2) {
      ruleForm.dateRange = null
    }
  }
  
  // 根据年级筛选学科
  const filterSubjects = () => {
    if (ruleForm.level) {
      const selectedLevel = Number(ruleForm.level)
      filteredSubjects.value = subjectList.value
        .filter(item => item.level === selectedLevel)
    } else {
      filteredSubjects.value = []
    }
  }
  
  // 监听年级变化
  watch(() => ruleForm.level, () => {
    filterSubjects()
    ruleForm.subject = ''
  })
  
  // 加载学科数据
  const loadSubjects = async () => {
    try {
      loading.value = true
      const response = await getSubjectList()
      
      if (response?.code === 1 && Array.isArray(response?.response)) {
        subjectList.value = response.response
        filterSubjects()
      } else {
        console.error('获取学科列表失败:', response)
        subjectList.value = []
        filteredSubjects.value = []
      }
    } catch (error) {
      console.error('加载学科列表失败:', error)
      subjectList.value = []
      filteredSubjects.value = []
    } finally {
      loading.value = false
    }
  }
  
  // 添加标题
  const addTitle = () => {
    ruleForm.titles.push({ 
      value: '',
      questions: [] 
    })
  }
  
  // 删除标题
  const removeTitle = (index: number) => {
    ruleForm.titles.splice(index, 1)
  }
  
  // 打开添加题目对话框
  const addQuestions = (index: number) => {
    currentTitleIndex.value = index
    if (addQuestionDialogRef.value) {
      addQuestionDialogRef.value.openDialog()
    }
  }
  
  // 处理添加的题目 - 关键修改点
  const handleAddQuestions = (questions: QuestionItem[]) => {
    if (currentTitleIndex.value === -1) return
    
    // 添加到当前标题
    const currentTitle = ruleForm.titles[currentTitleIndex.value]
    
    // 避免重复添加
    const newQuestions = questions.filter(q => 
      !currentTitle.questions.some(existing => existing.id === q.id)
    )
    
    if (newQuestions.length === 0) {
      ElMessage.warning('所选题目已存在')
      return
    }
    
    // 将题目添加到当前标题，使用 shortTitle 作为题干内容
    currentTitle.questions.push(...newQuestions.map(q => ({
      id: q.id,
      questionType: q.questionType,
      content: q.shortTitle, // 使用题目的 shortTitle 作为题干内容
      difficulty: q.difficult
    })))
    
    ElMessage.success(`成功添加 ${newQuestions.length} 个题目`)
  }
  
  // 移除题目
  const removeQuestion = (titleIndex: number, questionIndex: number) => {
    ruleForm.titles[titleIndex].questions.splice(questionIndex, 1)
    ElMessage.success('题目已移除')
  }
  
  const rules = ref<FormRules>({
    name: [
      { required: true, message: '请输入试卷名称', trigger: 'blur' },
      { min: 2, max: 50, message: '长度应在2到50个字符之间', trigger: 'blur' },
    ],
    level: [
      {
        required: true,
        message: '请选择年级',
        trigger: 'change',
      },
    ],
    subject: [
      {
        required: true,
        message: '请选择学科',
        trigger: 'change',
      },
    ],
    paperType: [
      {
        required: true,
        message: '请选择试卷类型',
        trigger: 'change',
      }
    ],
    duration: [
      { required: true, message: '请输入建议时长', trigger: 'blur' },
      { pattern: /^[1-9]\d*$/, message: '请输入大于0的整数', trigger: 'blur' }
    ],
    dateRange: [
      {
        type: 'array',
        required: ruleForm.paperType === 2,
        message: '请选择日期范围',
        trigger: 'change',
      }
    ]
  })
  
  // 初始化加载数据
  onMounted(() => {
    loadSubjects()
  })
  
  const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
      if (valid) {
        console.log('表单数据:', ruleForm)
        
        // 检查是否有标题但没有添加题目
        const hasTitleWithoutQuestions = ruleForm.titles.some(
          title => title.value.trim() !== '' && title.questions.length === 0
        )
        
        if (hasTitleWithoutQuestions) {
          ElMessage.warning('请为每个标题添加至少一个题目')
          return
        }
        
        if (ruleForm.paperType === 2 && ruleForm.dateRange) {
          const [startDate, endDate] = ruleForm.dateRange
          console.log('开始日期:', startDate)
          console.log('结束日期:', endDate)
        }
        
        // 模拟提交成功
        ElMessage({
          message: '试卷添加成功',
          type: 'success'
        })
        router.push('/shijuanlist')
      } else {
        console.log('表单验证失败:', fields)
      }
    })
  }
  
  const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
    ruleForm.dateRange = null
    ruleForm.paperType = 1
    // 重置标题数组
    ruleForm.titles = []
    filterSubjects()
  }
  </script>
  
  <style scoped>
  .add-shijuan-container {
    padding: 20px;
    max-width: 900px;
  }
  
  .compact-form .el-form-item {
    margin-bottom: 16px;
  }
  
  .dynamic-title-item.compact {
    margin-bottom: 12px;
    padding: 8px 0;
    border-top: 1px solid #eee;
  }
  
  .title-content {
    display: flex;
    gap: 8px;
    margin-bottom: 8px;
    align-items: center;
  }
  
  .title-actions {
    display: flex;
    gap: 6px;
  }
  
  /* 题目列表 - 紧凑布局 */
  .questions-list.compact {
    margin-top: 6px;
    width: 100%;
  }
  
  /* 修改：题目项布局 */
  .question-item.compact {
    margin-bottom: 8px;
    padding: 8px;
    border-radius: 4px;
    background-color: #f8f9fa;
    border: 1px solid #eee;
  }
  
  .question-content-wrapper {
    display: flex;
    align-items: flex-start;
    gap: 8px;
    width: 100%;
  }
  
  .question-index {
    font-weight: bold;
    min-width: 24px;
  }
  
  .question-text {
    flex: 1;
    white-space: pre-wrap; /* 允许换行 */
    word-break: break-word; /* 允许在单词内换行 */
  }
  
  /* 修改：题目操作按钮 */
  .question-actions {
    margin-left: auto; /* 将删除按钮推到右侧 */
  }
  
  .form-actions {
    margin-top: 16px;
    padding-top: 12px;
    border-top: 1px solid #eee;
  }
  
  /* 紧凑按钮 */
  .el-button--small {
    padding: 5px 10px;
    font-size: 12px;
  }
  </style>